import axios, { AxiosInstance, AxiosError, AxiosResponse, InternalAxiosRequestConfig } from 'axios';

// 创建 Axios 实例
const service: AxiosInstance = axios.create({
    baseURL: 'http://localhost:8080', // 可以根据你的后端 API 地址进行调整
    timeout: 5000,
});

// 请求拦截器
service.interceptors.request.use(
    (config: InternalAxiosRequestConfig) => {
        const token = localStorage.getItem('token'); // 从 localStorage 获取 token
        if (token) {
            config.headers['Authorization'] = `Bearer ${token}`; // 添加 Authorization 头
        }
        return config;
    },
    (error: AxiosError) => {
        console.log('请求错误:', error);
        return Promise.reject(error);
    }
);

// 响应拦截器
service.interceptors.response.use(
    (response: AxiosResponse) => {
        if (response.status === 200) {
            return response.data;
        } else {
            return Promise.reject('响应错误');
        }
    },
    (error: AxiosError) => {
        console.log('响应错误:', error);
        return Promise.reject(error);
    }
);

export default service;
